package com.myxy.mylogin;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getCanonicalName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initSharedPreferenc();//检验是否登录
        clear();
    }

    private void initSharedPreferenc(){
        //Context.MODE_PRIVATE 标识为允许SharedPreferences读写操作
        //Context.MODE_APPEND 标识为允许SharedPreferences追加内容
        //Context.MODE_WORLD_READABLE 标识为允许SharedPreferences只能读写
        //Context.MODE_WORLD_WRITEABLE 标识为允许SharedPreferences只能写入
        SharedPreferences sp = getSharedPreferences("app_login", Context.MODE_PRIVATE);
        //获取SharedPreference内的数据时，需要指定默认值
        String userAdmin = sp.getString("user_admin","未找到");

        //登录状态
        boolean hasBalance = sp.contains("user_type");

        TextView username = findViewById(R.id.user_name);

        if(hasBalance){//判断用户是否登录
            username.setText("欢迎"+userAdmin+"登录");
        }else{
            Toast.makeText(MainActivity.this,
                    "请先登录",Toast.LENGTH_SHORT).show();
            //创建Intent
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            startActivity(intent);
        }

        //清空SharedPreference内的所有数据，但不删除SharedPreference文件
        /*editor.clear();
        editor.apply();*/
    }
    private void clear(){
        Button xiaohui = findViewById(R.id.but_xiaohui);

        xiaohui.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferences sp = getSharedPreferences("app_login", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();

                editor.putString("user_type",null);//登录状态
                //3.提交到SharedPreferences文件
                //apply();为异步提交，不影响主线程
                editor.apply();

                Toast.makeText(MainActivity.this,
                        "销毁成功",Toast.LENGTH_SHORT).show();
                //创建Intent
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                startActivity(intent);
            }
        });
    }

}